import axios from 'axios'
import { refreshToken } from './server'

var instance = axios.create({
  baseURL: 'http://localhost:3000/',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    //从本地获取短token和长token
    const accessToken = localStorage.getItem('accessToken')
    const refreshToken = localStorage.getItem('refreshToken')
    //设置请求头
    config.headers.accessToken = accessToken
    config.headers.refreshToken = refreshToken
    return config
  },
  function (error) {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    //对响应数据做点什么
    if (response.data.code === 401) {
      console.log(response.data.code)
      //刷新token,短token刷新之后用长token刷新获取新的token
      refreshToken()
    }
    return response
  },
  function (error) {
    //对响应数据做点什么
    return Promise.reject(error)
  }
)

export default instance


export const httpSever = ({ method = '', url = '', data = {}, params = {} }) => {
  return new Promise((resolve, reject) => {
    instance({
      method,
      url,
      data,
      params
    })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
